package com.gthncz.xxhelper.service;

import android.content.Context;

import com.gthncz.xxhelper.greendao.ClientDBHelper;
import com.gthncz.xxhelper.greendao.DaoSession;
import com.gthncz.xxhelper.greendao.Subject;
import com.gthncz.xxhelper.greendao.SubjectDao;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 数据访问层服务
 * Created by GT on 2019/11/11.
 */

public class DAOService {

    private ClientDBHelper dbHelper;

    public DAOService(Context context){
        dbHelper = ClientDBHelper.getInstance(context);
    }

    /**
     * 利用关键字查找相关题目
     *
     * @param keywords
     * @return
     */
    public List<Subject> findSubjectByKeywords(String[] keywords) {
        if (keywords.length == 0) return new ArrayList<>();
        DaoSession daoSession = dbHelper.getDaoSession();
        SubjectDao subjectDao = daoSession.getSubjectDao();
        QueryBuilder<Subject> builder = subjectDao.queryBuilder();
        WhereCondition[] conditions = new WhereCondition[keywords.length];

        for (int i=0; i<keywords.length; ++i){
            String keyword = keywords[i];
            conditions[i] =
                    builder.or(
                            // Java String.format 中使用 '%' 对 '%' 进行转义
                            SubjectDao.Properties.Question.like(String.format("%%%s%%", keyword)),
                            SubjectDao.Properties.OptionA.like(String.format("%%%s%%", keyword)),
                            SubjectDao.Properties.OptionB.like(String.format("%%%s%%", keyword)),
                            SubjectDao.Properties.OptionC.like(String.format("%%%s%%", keyword)),
                            SubjectDao.Properties.OptionD.like(String.format("%%%s%%", keyword))
                    );
        }

        for(WhereCondition condition: conditions){
            builder.where(condition);
        }

        /*
        if (keywords.length == 1){
            builder.where(conditions[0]);
        } else if (keywords.length == 2){
            builder.whereOr(conditions[0], conditions[1]);
        } else if (keywords.length > 3){
            builder.whereOr(conditions[0], conditions[1], Arrays.copyOfRange(conditions, 2, conditions.length));
        }
        */
        builder.orderAsc(SubjectDao.Properties.Id);
        return builder.list();
    }

}
